package dao.impl;

import dao.UserDao;
import entity.Order;
import entity.User;
import org.hibernate.Criteria;
import org.hibernate.Session;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import util.DBUtils;

import java.util.List;
import java.util.Set;

public class UserDaoImpl extends EntityDaoImpl<User> implements UserDao {
    public UserDaoImpl(Class<User> userClass) {
        super(userClass);
    }

    @Override
    public User getByUsername(String username) {
        Session session = sessionFactory.openSession();
        List<User> users = null;
        try {
            Query products = session.createQuery("from User where username = :username ");
            products.setParameter("username",username);
            users = products.list();
            if(users!=null&&users.size()>0){
                User user = users.get(0);
                Set<Order> orders = user.getOrders();
                for (Order order : orders) {
                    System.out.println(order);
                }
                return user;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        return null;
    }

    @Override
    public User getNamePasswordByUsername(String username) {
        Session session = sessionFactory.openSession();
        List<User> users = null;
        try {
            Query products = session.createQuery("select new User(u.name,u.password) from User u where username = :username ");
            products.setParameter("username",username);
            users = products.list();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        if(users!=null&&users.size()>0){
            return users.get(0);
        }
        return null;
    }

    @Override
    public List<User> getUsersByNameLikeKeyword(String keyword) {
        Session session = sessionFactory.openSession();

        //创建qbc
        Criteria criteria = session.createCriteria(User.class);
        Criteria add = criteria.add(Restrictions.like("name", keyword, MatchMode.ANYWHERE));
        List<User> list = add.list();

        session.close();
        return list;
    }
}
